﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CSharpIrcBot.Forms
{
    public partial class frmOptions : Form
    {
        SortedList<ListViewItem, TabPage> slListViewToTabPage;

        public Connection SelectedConnection
        {
            get { return ucConnectionOptions1.Connection; }
        }

        public frmOptions()
        {
            InitializeComponent();
            PopulateListViewToTabPage();
        }

        private void PopulateListViewToTabPage()
        {
            if( slListViewToTabPage == null )
            {
                slListViewToTabPage = new SortedList<ListViewItem, TabPage>();
            }
            slListViewToTabPage.Add( GetListViewItemFromListView( "Connections", this.lvOptionList ), tpConnections );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="text">Displayed Text</param>
        /// <param name="lsv">ListView</param>
        /// <returns></returns>
        private ListViewItem GetListViewItemFromListView( string text, ListView lsv )
        {
            foreach( ListViewItem lvi in lsv.Items )
            {
                if( lvi.Text == text )
                {
                    return lvi;
                }
            }
            return null;
        }

        private void lvOptionList_SelectedIndexChanged( object sender, EventArgs e )
        {
            if(sender == null || !(sender is ListView))
            {
                return;
            }

            ListView lsv = sender as ListView;

            if( lsv.SelectedItems.Count != 1 )
            {
                return;
            }

            ListViewItem lvi = lsv.SelectedItems[0];

            TabPage tpg = slListViewToTabPage[lvi];

            tcOptions.SelectedTab = tpg;
        }

        private void btnCancel_Click( object sender, EventArgs e )
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnSave_Click( object sender, EventArgs e )
        {
            this.btnApply.PerformClick();
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnApply_Click( object sender, EventArgs e )
        {
            ucConnectionOptions1.SaveConnections();
            Global.ConnectionInfo = ucConnectionOptions1.Connection.GetConnectionArgs();
        }
    }
}
